import time

from django.db import transaction
from django.http import JsonResponse, HttpResponse
from django.utils.datetime_safe import datetime

from submission.models import *
from question.models import Question, Questionnaire, Choice

from backend.tools import checkQuestionnaireTime, checkAnswer
import json
import xlwt


# Create your views here.
class SubmissionViews:
    @staticmethod
    # 创建新的提交记录
    def createSubmission(request):
        response = {'code': 0, 'msg': 'success'}
        if request.method == 'POST':
            data = json.loads(request.body)

            questionnaireID = data.get("questionnaireID")
            ip = data.get('ip')
            username = data.get('username')

            submitUID = username if username else ip
            questionnaire = Questionnaire.objects.get(id=questionnaireID)
            checkQuestionnaireTime(questionnaire)
            settings = questionnaire.Settings

            submission = Submission.objects.filter(IPaddress=ip, questionnaireTo_id=questionnaireID, isSubmitted=False)
            if submission.exists():
                # response["code"] = -1
                response["msg"] = "当前IP有未完成的作答"
                response["submissionID"] = submission.first().id
                return JsonResponse(response)

            if settings.IPLimit:
                existSubmission = Submission.objects.filter(IPaddress=ip, questionnaireTo_id=questionnaireID,
                                                            isSubmitted=True)
                if existSubmission.exists() and existSubmission.first().isSubmitted:
                    response["code"] = -1
                    response["msg"] = "当前IP已经提交过问卷了"
                    response["submissionID"] = existSubmission.first().id
                    return JsonResponse(response)

            if settings.StartTime is not None:
                if settings.StartTime > datetime.now():
                    response["code"] = -1
                    response["msg"] = "未到开始时间"
                    return JsonResponse(response)
            if settings.DeadLine is not None:
                if settings.DeadLine < datetime.now():
                    response["code"] = -1
                    response["msg"] = "超出截止时间"
                    return JsonResponse(response)

            try:
                if questionnaire.Type == 1:  # 普通问卷
                    newSubmission = Submission.objects.create(submitUID=submitUID,
                                                              questionnaireTo_id=questionnaireID, IPaddress=ip)
                    newSubmission.save()
                    response['submissionID'] = newSubmission.pk
                    return JsonResponse(response)
                elif questionnaire.Type == 2:  # 投票问卷
                    existSubmissions = Submission.objects.filter(IPaddress=ip, questionnaireTo_id=questionnaireID,
                                                                 isSubmitted=False)
                    if existSubmissions:
                        for existSubmission in existSubmissions:
                            existSubmission.delete()
                    newSubmission = Submission.objects.create(submitUID=submitUID,
                                                              questionnaireTo_id=questionnaireID, IPaddress=ip)
                    newSubmission.save()
                    response['submissionID'] = newSubmission.pk
                    return JsonResponse(response)
                elif questionnaire.Type == 3:  # 报名问卷
                    with transaction.atomic():
                        cnt = Submission.objects.filter(questionnaireTo_id=questionnaireID, isSubmitted=True).count()
                        if settings.Times and cnt >= settings.Times:
                            response["code"] = -1
                            response["msg"] = "报名问卷填写数已达上限"
                            return JsonResponse(response)
                        existSubmissions = Submission.objects.filter(IPaddress=ip, questionnaireTo_id=questionnaireID,
                                                                 isSubmitted=False)
                        if existSubmissions:
                            for existSubmission in existSubmissions:
                                existSubmission.delete()
                        newSubmission = Submission.objects.create(submitUID=submitUID,
                                                              questionnaireTo_id=questionnaireID, IPaddress=ip)
                        newSubmission.save()
                        response['submissionID'] = newSubmission.pk
                    return JsonResponse(response)
                elif questionnaire.Type == 4:  # 考试问卷
                    newSubmission = Submission.objects.create(submitUID=submitUID,
                                                              questionnaireTo_id=questionnaireID, IPaddress=ip)
                    newSubmission.save()
                    response['submissionID'] = newSubmission.pk
                    return JsonResponse(response)
                elif questionnaire.Type == 5:  # 打卡问卷
                    newSubmission = Submission.objects.create(submitUID=submitUID,
                                                              questionnaireTo_id=questionnaireID, IPaddress=ip)
                    newSubmission.save()
                    response['submissionID'] = newSubmission.pk
                    return JsonResponse(response)
            except:
                response["code"] = -1
                response["msg"] = "系统异常，创建答卷失败"
                return JsonResponse(response)
        else:
            response["code"] = -1
            response["msg"] = "请使用POST方法调用"
            return JsonResponse(response)

    @staticmethod
    # 删除提交记录
    def deleteSubmission(request):
        response = {'code': 0, 'msg': 'success'}
        if request.method == 'POST':
            data = json.loads(request.body)

            submitUID = data.get("submitUID")
            questionnaireID = data.get("questionnaireID")

            submissionID = data.get("submissionID")

            if submissionID is not None:
                try:
                    Submission.objects.get(pk=submissionID).delete()
                    return JsonResponse(response)
                except:
                    response["code"] = -1
                    response["msg"] = "答卷不存在"
                    return JsonResponse(response)
            elif Submission.objects.filter(submitUID=submitUID, questionnaireTo_id=questionnaireID).exists():
                try:
                    Submission.objects.get(submitUID=submitUID, questionnaireTo_id=questionnaireID).delete()
                    return JsonResponse(response)
                except:
                    response["code"] = -1
                    response["msg"] = "答卷不存在"
                    return JsonResponse(response)
            else:
                response["code"] = -1
                response["msg"] = "答卷不存在"
                return JsonResponse(response)
        else:
            response["code"] = -1
            response["msg"] = "请使用POST方法调用"
            return JsonResponse(response)

    @staticmethod
    # 提交问卷
    def submitQuestionnaire(request):
        response = {'code': 0, 'msg': 'success'}
        if request.method == 'POST':
            data = json.loads(request.body)

            submissionID = data.get("submissionID")

            if submissionID:
                try:
                    submissionObj = Submission.objects.get(id=submissionID)
                    questionnaire = submissionObj.questionnaireTo
                    settings = questionnaire.Settings
                    checkQuestionnaireTime(questionnaire)
                    if submissionObj.isSubmitted:
                        response["code"] = -1
                        response["msg"] = "不可重复提交答卷"
                        return JsonResponse(response)
                except:
                    response["code"] = -1
                    response["msg"] = "提交失败"
                    return JsonResponse(response)
            else:
                response["code"] = -1
                response["msg"] = "未找到作答记录"
                return JsonResponse(response)
            if settings.StartTime is not None:
                if settings.StartTime > datetime.now():
                    response["code"] = -1
                    response["msg"] = "未到开始时间"
                    return JsonResponse(response)
            if settings.DeadLine is not None:
                if settings.DeadLine < datetime.now():
                    response["code"] = -1
                    response["msg"] = "超出截止时间"
                    return JsonResponse(response)

            notNullQuestions = Question.objects.filter(Must=True, Questionnaire=submissionObj.questionnaireTo)
            nullQuestionList = []
            for notNullQuestion in notNullQuestions:
                if not Answer.objects.filter(questionTo=notNullQuestion, submissionTo=submissionObj).exists():
                    nullQuestionList.append(notNullQuestion.id)
            if not len(nullQuestionList) == 0:
                response["code"] = -1
                response["msg"] = "必答问题未作答"
                response['nullQuestionList'] = nullQuestionList
                return JsonResponse(response)

            if questionnaire.Type == 1:
                pass
            elif questionnaire.Type == 2:
                pass
            elif questionnaire.Type == 3:
                questions = Question.objects.filter(Questionnaire=questionnaire)
                with transaction.atomic():
                    for question in questions:
                        if question.Type not in [8, 9]:
                            continue
                        choiceCountDict = {}
                        choices = Choice.objects.filter(Question=question)
                        for choice in choices:
                            choiceCountDict[choice.id] = choice.Times
                        # 排序
                        answers = Answer.objects.filter(questionTo=question).order_by('submissionTo_id')
                        for answer in answers:
                            choices = answer.answerChoices.all()
                            for choice in choices:
                                choiceCountDict[choice.id] -= 1
                                if choiceCountDict[choice.id] < 0:
                                    response["code"] = -1
                                    response["msg"] = "报名已满"
                                    return JsonResponse(response)
                    # cnt = Submission.objects.filter(questionnaireTo=questionnaire, isSubmitted=True).count()
                    # if settings.Times and cnt >= settings.Times:
                    #     response["code"] = -1
                    #     response["msg"] = "报名已满"
                    #     return JsonResponse(response)
                    submissionObj.isSubmitted = True
                    submissionObj.save()
            elif questionnaire.Type == 4:
                checkAnswer(submissionObj)
            elif questionnaire.Type == 5:
                pass

            if not submissionObj.isSubmitted:
                submissionObj.isSubmitted = True
                submissionObj.save()
            response['info'] = {'submissionID': submissionObj.id,
                                'questionnaireID': submissionObj.questionnaireTo.id,
                                'submitUID': submissionObj.submitUID,
                                'submitTime': submissionObj.submitTime.strftime("%Y-%m-%d %H:%M:%S")}
            return JsonResponse(response)
        else:
            response["code"] = -1
            response["msg"] = "请使用POST方法调用"
            return JsonResponse(response)

    @staticmethod
    # 获取答卷信息
    def getSubmissionAnswers(request):
        response = {'code': 0, 'msg': 'success'}
        if request.method == 'POST':
            data = json.loads(request.body)

            submissionID = data.get("submissionID")
            if submissionID is not None:
                try:
                    submissionObj = Submission.objects.get(id=submissionID)
                except:
                    response["code"] = -1
                    response["msg"] = "未找到匹配的答题记录"
                    return JsonResponse(response)
            else:
                response["code"] = -1
                response["msg"] = "未找到匹配的答题记录"
                return JsonResponse(response)

            response['info'] = {'submitUID': submissionObj.submitUID, 'isSubmitted': submissionObj.isSubmitted,
                                'createTime': submissionObj.createTime.strftime("%Y-%m-%d %H:%M:%S"),
                                'submitTime': submissionObj.submitTime.strftime("%Y-%m-%d %H:%M:%S"),
                                'answerTime': (submissionObj.submitTime - submissionObj.createTime).seconds,
                                'Type': submissionObj.questionnaireTo.Type}

            answerObjs = Answer.objects.filter(submissionTo=submissionObj)
            response['answerList'] = []
            for answerObj in answerObjs:
                answer = {'answerid': answerObj.pk, 'Type': answerObj.questionTo.Type,
                          'questionid': answerObj.questionTo.id}
                if answerObj.questionTo.Type in [1, 2, 6, 7, 8, 9, 10, 11]:
                    answer['choiceIDList'] = []
                    selections = answerObj.answerChoices.all()
                    for selection in selections:
                        answer['choiceIDList'].append(selection.pk)
                elif answerObj.questionTo.Type in [3, 5, 12]:
                    answer['answerText'] = answerObj.answerText
                elif answerObj.questionTo.Type == 4:
                    answer['answerScore'] = answerObj.answerScore
                response['answerList'].append(answer)
            return JsonResponse(response)
        else:
            response["code"] = -1
            response["msg"] = "请使用POST方法调用"
            return JsonResponse(response)

    @staticmethod
    # 保存问题答案
    def saveAnswer(request):
        response = {'code': 0, 'msg': 'success'}
        if request.method == 'POST':
            data = json.loads(request.body)

            submissionID = data.get('submissionID')  # 所属的提交记录
            questionID = data.get('questionID')  # 对应的问题

            question = Question.objects.get(id=questionID)
            questiontype = question.Type  # 问题的类型

            checkQuestionnaireTime(question.Questionnaire)

            # save_id = transaction.savepoint()

            try:
                submission = Submission.objects.get(id=submissionID)
                if submission.isSubmitted:
                    response["code"] = -1
                    response["msg"] = "答卷已经提交，无法保存答案"
                    return JsonResponse(response)

                settings = submission.questionnaireTo.Settings
                if submission.questionnaireTo.Type == 4:
                    if settings is not None:
                        if settings.AnswerTime:
                            if (datetime.now() - submission.createTime).seconds > settings.AnswerTime:
                                submission.isSubmitted = True
                                submission.save()
                                response["code"] = -1
                                response["msg"] = "答题时间已到，已经自动提交"
                                return JsonResponse(response)

                if settings is not None:
                    if settings.DeadLine is not None:
                        if datetime.now() > settings.DeadLine:
                            submission.isSubmitted = True
                            submission.save()
                            response["code"] = -1
                            response["msg"] = "答题时间已到，已经自动提交"
                            return JsonResponse(response)

                if Answer.objects.filter(submissionTo=submission, questionTo_id=questionID).exists():
                    newAnswerObj = Answer.objects.filter(submissionTo=submission, questionTo_id=questionID).first()
                else:
                    newAnswerObj = Answer.objects.create(submissionTo=submission, questionTo_id=questionID)
                    newAnswerObj.save()
                # 单选或多选
                if questiontype in [1, 2, 6, 7, 8, 9, 10, 11]:
                    answerSelectionIDSet = data.get('answerSelectionIDSet')
                    if answerSelectionIDSet:
                        for answerSelectionID in answerSelectionIDSet:
                            answerSelectionObj = Choice.objects.get(pk=answerSelectionID)
                            newAnswerObj.answerChoices.add(answerSelectionObj)
                            newAnswerObj.save()
                        return JsonResponse(response)
                    else:
                        response["code"] = -1
                        response["msg"] = "参数非法"
                        return JsonResponse(response)
                elif questiontype in [3, 5, 12]:
                    answerText = data.get('answerText')
                    if answerText:
                        newAnswerObj.answerText = answerText
                        newAnswerObj.save()
                        return JsonResponse(response)
                    else:
                        response["code"] = -1
                        response["msg"] = "参数非法"
                        return JsonResponse(response)
                elif questiontype == 4:
                    answerScore = data.get('answerScore')
                    if answerScore is not None:
                        newAnswerObj.answerScore = answerScore
                        newAnswerObj.save()
                        return JsonResponse(response)
                    else:
                        response["code"] = -1
                        response["msg"] = "参数非法"
                        return JsonResponse(response)
            except:
                response["code"] = -1
                response["msg"] = "系统异常"
                return JsonResponse(response)
        else:
            response["code"] = -1
            response["msg"] = "请使用POST方法调用"
            return JsonResponse(response)

    @staticmethod
    def getAllSubmissions(request):
        response = {'code': 0, 'msg': 'success'}
        if request.method == 'POST':
            data = json.loads(request.body)
            questionnaireID = data.get('questionnaireID')
            submissions = Submission.objects.filter(questionnaireTo_id=questionnaireID, isSubmitted=True)
            # submissionHeadList = ['问卷编号', '提交者ID', '开始时间', '结束时间']
            questionnaire = Questionnaire.objects.get(id=questionnaireID)

            questionObjs = Question.objects.filter(Questionnaire=questionnaire).order_by('Number')

            # for questionObj in questionObjs:
            #     submissionHeadList.append((questionObj.Stem) + ('(*)' if questionObj.Must else ''))

            response['submissions'] = []
            for submission in submissions:
                submissionInfoDict = {
                    '问卷编号': submission.pk,
                    '提交者ID': submission.submitUID,
                    '提交者IP': submission.IPaddress,
                    '开始时间': submission.createTime.strftime("%Y-%m-%d %H:%M:%S"),
                    '提交时间': submission.submitTime.strftime("%Y-%m-%d %H:%M:%S"),
                    '作答耗时': (submission.submitTime - submission.createTime).seconds,
                }

                # 选项详细信息
                for questionObj in questionObjs:
                    if Answer.objects.filter(questionTo=questionObj, submissionTo=submission).exists():
                        ansobj = Answer.objects.get(questionTo=questionObj, submissionTo=submission)
                        if ansobj.questionTo.Type in [1, 2, 6, 7, 8, 9, 10, 11]:
                            choices = ansobj.answerChoices.all()
                            if choices is not None:
                                text = ''
                                for choice in choices:
                                    text += choice.Text
                                    text += ';'
                                submissionInfoDict[questionObj.id] = text
                                # submissionInfoList.append(text)
                            else:
                                submissionInfoDict[questionObj.id] = '(空)'
                                # submissionInfoList.append('(空)')
                        elif ansobj.questionTo.Type in [3, 5, 12]:
                            submissionInfoDict[questionObj.id] = ansobj.answerText
                            # submissionInfoList.append(ansobj.answerText)
                        elif ansobj.questionTo.Type == 4:
                            submissionInfoDict[questionObj.id] = ansobj.answerScore
                            # submissionInfoList.append(ansobj.answerScore)
                    else:
                        submissionInfoDict[questionObj.id] = '(空)'
                        # submissionInfoList.append('(空)')
                response['submissions'].append(submissionInfoDict)

            return JsonResponse(response)
        else:
            response["code"] = -1
            response["msg"] = "请使用POST方法调用"
            return JsonResponse(response)


class ReportViews:

    @staticmethod
    def exportExcel(request):
        # response = {'code': 0, 'msg': 'success'}
        # data = request.POST
        data = json.loads(request.body)

        questionnaireID = data.get('questionnaireID')

        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=' + time.strftime("%Y%m%d%H%M%S",
                                                                                  time.localtime()) + str(
            questionnaireID) + '.xls'
        # 拿到对应的全部问卷
        submissions = Submission.objects.filter(questionnaireTo_id=questionnaireID)
        # 对应的问题作为列

        wb = xlwt.Workbook(encoding='utf-8')
        w = wb.add_sheet('sheet1')
        i = 0
        j = 0
        submissionHeadList = ['问卷编号', 'IP地址', '提交者ID', '开始时间', '结束时间']

        questionnaire = Questionnaire.objects.get(id=questionnaireID)

        if questionnaire.Type == 4:
            submissionHeadList.append('得分')

        # if questionnaire.Type == 4:
        #     green = xlwt.Pattern()
        #     green.pattern = xlwt.Pattern.SOLID_PATTERN
        #     green.pattern_back_colour = 3
        #
        #     red = xlwt.Pattern()
        #     red.pattern = xlwt.Pattern.SOLID_PATTERN
        #     red.pattern_back_colour = 2
        #
        #     yellow = xlwt.Pattern()
        #     yellow.pattern = xlwt.Pattern.SOLID_PATTERN
        #     yellow.pattern_back_colour = 5
        #
        #     white = xlwt.Pattern()
        #     white.pattern = xlwt.Pattern.SOLID_PATTERN
        #     white.pattern_back_colour = 0

        questionObjs = Question.objects.filter(Questionnaire=questionnaire).order_by('Number')

        for questionObj in questionObjs:
            submissionHeadList.append((questionObj.Stem) + ('(*)' if questionObj.Must else ''))

        for sh in submissionHeadList:
            w.write(0, j, sh)
            j = j + 1
        i += 1
        for submission in submissions:
            j = 0
            submissionInfoList = [
                submission.pk,
                submission.submitUID,
                submission.IPaddress,
                # '已提交' if submission.isSubmitted else '未提交',
                submission.createTime.strftime("%Y-%m-%d %H:%M:%S"),
                submission.submitTime.strftime("%Y-%m-%d %H:%M:%S"),
                # time.strftime("%Y%m%d%H%M%S", submission.createTime),
                # time.strftime("%Y%m%d%H%M%S", submission.submitTime),
            ]
            if submission.questionnaireTo.Type == 4:
                submissionInfoList.append(submission.grade)
            # 选项详细信息
            for si in submissionInfoList:
                w.write(i, j, si)
                j = j + 1
            for questionObj in questionObjs:
                if Answer.objects.filter(questionTo=questionObj, submissionTo=submission).exists():
                    ansobj = Answer.objects.get(questionTo=questionObj, submissionTo=submission)
                    if ansobj.questionTo.Type in [1, 2, 6, 7, 8, 9]:
                        choices = ansobj.answerChoices.all()
                        if choices is not None:
                            text = ''
                            for choice in choices:
                                text += choice.Text
                                text += ';'
                            w.write(i, j, text)
                        else:
                            w.write(i, j, '(空)')
                    elif ansobj.questionTo.Type in [10, 11]:
                        choices = ansobj.answerChoices.all()
                        if choices is not None:
                            text = ''
                            for choice in choices:
                                text += choice.Text
                                text += ';'
                            if ansobj.gradeStatus == 0:
                                text += "(0')"
                                w.write(i, j, text)
                                # w.write(i, j, text, style=red)
                            elif ansobj.gradeStatus == 1:
                                text += '(' + ansobj.questionTo.HalfScore + "')"
                                w.write(i, j, text)
                                # w.write(i, j, text, style=yellow)
                            elif ansobj.gradeStatus == 2:
                                text += '(' + ansobj.questionTo.Score + "')"
                                w.write(i, j, text)
                                # w.write(i, j, text, style=green)
                    elif ansobj.questionTo.Type in [3, 5, 12]:
                        w.write(i, j, ansobj.answerText)
                    elif ansobj.questionTo.Type == 4:
                        w.write(i, j, ansobj.answerScore)
                    j += 1
                else:
                    w.write(i, j, '(空)')
                    j += 1
            i += 1
        wb.save(response)

        # bio = BytesIO()
        # wb.save(bio)
        # bio.seek(0)
        # response['filename'] = time.strftime("%Y%m%d%H%M%S", time.localtime()) + str(questionnaireID) + '.xls'
        # response['b64data'] = base64.b64encode(bio.getvalue()).decode()

        return response
        # 将代表一条提交记录的一行信息写入表格中

    @staticmethod
    def getStatistic(request):
        response = {'code': 0, 'msg': 'success'}
        data = json.loads(request.body)

        questionnaireID = data.get('questionnaireID')

        # totalCount = Submission.objects.filter(questionnaireTo_id=questionnaireID).count()
        submittedCount = Submission.objects.filter(questionnaireTo_id=questionnaireID, isSubmitted=True).count()
        response['submittedCount'] = submittedCount

        # TODO:题号和ID双重排序
        questions = Question.objects.filter(Questionnaire_id=questionnaireID).order_by('Number')

        response['statistics'] = []
        for question in questions:
            questionStatisticList = {'questionID': question.id, 'Type': question.Type, 'Stem': question.Stem}
            if question.Type in [1, 2, 6, 7, 8, 9, 10, 11]:
                choices = Choice.objects.filter(Question=question)  # 该题目的所有选项
                choiceCountDict = {}
                choiceTextDict = {}
                for choice in choices:
                    choiceCountDict[choice.id] = choice.answer_set.filter(questionTo=question,
                                                                          submissionTo__isSubmitted=True).count()
                    choiceTextDict[choice.id] = choice.Text
                questionStatisticList['choiceCountDict'] = choiceCountDict
                questionStatisticList['choiceTextDict'] = choiceTextDict
            elif question.Type in [3, 5, 12]:
                answerCount = Answer.objects.filter(questionTo=question, submissionTo__isSubmitted=True).count()
                questionStatisticList['answerCount'] = answerCount
            elif question.Type == 4:
                answers = Answer.objects.filter(questionTo=question, submissionTo__isSubmitted=True)
                totalScore = 0
                for answer in answers:
                    totalScore += answer.answerScore
                averageScore = totalScore / submittedCount
                questionStatisticList['averageScore'] = averageScore
            response['statistics'].append(questionStatisticList)

        return JsonResponse(response)

    @staticmethod
    def getStatByQuestion(request):
        response = {'code': 0, 'msg': 'success'}
        data = json.loads(request.body)

        questionnaireID = data.get('questionnaireID')
        questionNumber = data.get('questionNumber')
        questionID = data.get('questionID')

        if questionNumber is not None and questionnaireID is not None:
            question = Question.objects.get(Questionnaire_id=questionnaireID, Number=questionNumber)

        elif questionID:
            question = Question.objects.get(id=questionID)

        else:
            response["code"] = -1
            response["msg"] = "问题不存在"
            return JsonResponse(response)

        answers = Answer.objects.filter(questionTo=question, submissionTo__isSubmitted=True).order_by('id')
        QesData = {'Type': question.Type, 'Qusetion': question.Stem, 'Describe': question.Describe,
                   'Must': question.Must, 'Total': answers.count()}
        if question.Type in [10, 11]:
            QesData['TrueAns'] = []
            choices = Choice.objects.filter(Question=question, IsTrueAnswer=True)
            for choice in choices:
                QesData['TrueAns'].append(choice.id)
        response['QesData'] = QesData
        if question.Type in [1, 2, 6, 7, 8, 9, 10, 11]:
            ChooseData = []
            choices = Choice.objects.filter(Question=question).order_by('id')
            i = 0
            for choice in choices:
                i += 1
                ChooseDatum = {'number': i, 'id': choice.id, 'name': choice.Text}
                ChooseDatum['value'] = choice.answer_set.filter(questionTo=question,
                                                                submissionTo__isSubmitted=True).count()
                ChooseData.append(ChooseDatum)
            response['ChooseData'] = ChooseData
        AnswerData = []
        for answer in answers:
            submission = answer.submissionTo
            AnswerDatum = {'submitUID': submission.submitUID,
                           'submitTime': submission.submitTime.strftime("%Y-%m-%d %H:%M:%S")}
            if answer.questionTo.Type in [1, 2, 6, 7, 8, 9, 10, 11]:
                AnswerDatum['choices'] = {}
                choices = answer.answerChoices.all()
                for choice in choices:
                    AnswerDatum['choices'][choice.id] = choice.Text
            elif answer.questionTo.Type in [3, 5, 12]:
                AnswerDatum['answerText'] = answer.answerText
            elif answer.questionTo.Type == 4:
                AnswerDatum['answerScore'] = answer.answerScore
            AnswerData.append(AnswerDatum)
        response['AnswerData'] = AnswerData
        return JsonResponse(response)

    @staticmethod
    def getChoiceAB(request):
        response = {'code': 0, 'msg': 'success'}
        data = json.loads(request.body)

        questionAID = data.get('questionAID')
        questionBID = data.get('questionBID')

        choiceAID = data.get('choiceAID')
        choiceBID = data.get('choiceBID')

        AList = []
        BList = []
        cnt = 0
        questionA = Question.objects.get(id=questionAID)
        answersA = Answer.objects.filter(questionTo=questionA)
        for answer in answersA:
            if answer.answerChoices.filter(id=choiceAID):
                AList.append(answer.submissionTo.id)

        questionB = Question.objects.get(id=questionBID)
        answersB = Answer.objects.filter(questionTo=questionB)
        for answer in answersB:
            if answer.answerChoices.filter(id=choiceBID):
                BList.append(answer.submissionTo.id)

        for a in AList:
            if a in BList:
                cnt += 1
        response['count'] = cnt
        return JsonResponse(response)

    @staticmethod
    def getScore(request):
        response = {'code': 0, 'msg': 'success'}
        data = json.loads(request.body)

        submissionID = data.get('submissionID')
        questionID = data.get('questionID')

        submission = Submission.objects.get(id=submissionID)
        try:
            answer = Answer.objects.get(submissionTo=submission, questionTo_id=questionID)
            response['gradeStatus'] = answer.gradeStatus
            response['answerScore'] = answer.answerScore
            return JsonResponse(response)
        except:
            response["code"] = -1
            response["msg"] = "答题记录不存在"
            return JsonResponse(response)


class EnrollViews:
    @staticmethod
    def getRemain(request):
        # 获取剩余名额
        response = {'code': 0, 'msg': 'success'}
        data = json.loads(request.body)

        questionnaireID = data.get('questionnaireID')
        questionNumber = data.get('questionNumber')

        questionID = data.get('questionID')

        if questionNumber is not None and questionnaireID is not None:
            question = Question.objects.get(Questionnaire_id=questionnaireID, Number=questionNumber)

        elif questionID:
            question = Question.objects.get(id=questionID)

        else:
            response["code"] = -1
            response["msg"] = "问题不存在"
            return JsonResponse(response)

        choiceCountDict = {}

        choices = Choice.objects.filter(Question=question)
        for choice in choices:
            choiceCountDict[choice.id] = choice.Times

        #for choice in choices:
            #choiceCountDict[choice.id] = choice.Times - choice.answer_set.all().filter(submissionTo__isSubmitted__in=[True]).count()
            # for answer in choice.answer_set.all().filter(submissionTo__isSubmitted__in=[True])

        #print(choiceCountDict)

        with transaction.atomic():
            answers = Answer.objects.filter(questionTo=question)
            for answer in answers:
                answerChoices = answer.answerChoices.all()
                for answerChoice in answerChoices:
                    print(str(answer.questionTo.id) + ' ' + str(answer.id) + ' ' + str(
                        answer.submissionTo.id) + ' ' + str(answerChoice.id))
                    choiceCountDict[answerChoice.id] -= 1
            print(choiceCountDict)

        response['choiceRemain'] = choiceCountDict
        return JsonResponse(response)